package com.ndood.oss.aliyun.web.controller;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.ndood.oss.aliyun.bean.ObjectVo;
import com.ndood.oss.aliyun.utils.AliyunOSS;

@Controller
@RequestMapping("/oss/aliyun")
public class FileUploadController {
	/**
	 * 去上传单个文件
	 */
	@GetMapping("/upload")
	public String toUploadPage() {
		return "oss/aliyun/upload";
	}

	/**
	 * 上传单个文件
	 */
	@PostMapping("/upload")
	@ResponseBody
	public Object uploadOneFile(@RequestParam("file") MultipartFile file) throws Exception {
		// Step1: 判断文件内容是否为空
		if (file == null || file.isEmpty()) {
			throw new Exception("文件内容为空!!!");
		}

		// Step2: 上传文件
		String url = AliyunOSS.getInstance().upload("ndood", "test/", file);

		// Step3: 返回结果
		return new ObjectVo("10000", "上传成功！", url);
	}

	/**
	 * 去上传多个文件
	 */
	@GetMapping("/uploads")
	public String toUploadsPage() {
		return "oss/aliyun/uploads";
	}

	/**
	 * 上传多个文件
	 */
	@PostMapping("/uploads")
	@ResponseBody
	public Object uploadFiles(HttpServletRequest request) throws Exception {
		// Step1: 对请求参数进行校验
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		if (fileMap == null || fileMap.size() == 0) {
			throw new Exception("文件内容为空!!!");
		}

		// Step2: 上传文件
		Collection<MultipartFile> files = fileMap.values();
		List<String> urls = new ArrayList<String>();
		for (MultipartFile file : files) {
			String url = AliyunOSS.getInstance().upload("ndood", "test/", file);
			urls.add(url);
		}

		// Step3: 返回结果
		return new ObjectVo("10000", "上传成功！", StringUtils.join(urls, ','));
	}
}
